package com.geaosu.filesselector;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;


/**
 * 首页
 */
public class HomeFragment extends Fragment {
    private GridView mGridView;
    private HomeFragmentAdapter mAdapter;
    private List<FileBean> mList = new ArrayList<>();


    public static Fragment open() {
        return new HomeFragment();
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mGridView = (GridView) view.findViewById(R.id.mGridView);

        mGridView.setAdapter(mAdapter = new HomeFragmentAdapter());
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                FileBean bean = mList.get(position);
                if (TextUtils.isEmpty(bean.getPath())) {
                    Toast.makeText(getActivity(), "无法打开，路径错误", Toast.LENGTH_SHORT).show();
                    return;
                }
                EventBus.getDefault().post(new DataEvent(DataEvent.Type.TO_NEXT_FOLDER, bean));
            }
        });
        mList.add(new FileBean("全部文件", "/sdcard/"));
        mList.add(new FileBean("最近使用", "/sdcard/download"));
        mList.add(new FileBean("下载", "/"));
        mList.add(new FileBean("图片", "/"));
        mList.add(new FileBean("音乐", "/"));
        mList.add(new FileBean("视频", "/"));
        mList.add(new FileBean("文稿", "/"));
        mList.add(new FileBean("安装包", "/"));
        mList.add(new FileBean("压缩包", "/"));
        mAdapter.replaceAll(mList);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        EventBus.getDefault().unregister(this);
    }

    /**
     * EventBus 数据和事件分发
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DataEvent event) {

    }
}
